package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityMachinePublishInBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.link.entity.PublicTypeEntity;
import com.sgb.kjwl.model.entity.SuccessEntity;
import com.sgb.kjwl.model.entity.user.AddChildEntity;
import com.sgb.kjwl.model.entity.user.AddMachineInEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.DictEntity;
import com.sgb.kjwl.model.entity.user.PayType;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.MachinePublishEvent;
import com.sgb.kjwl.view.ui.activity.self.authentication.CommitSuccessActivity;
import com.swgk.core.view.CityPickBuilder;
import com.swgk.core.view.CityPickView;
import com.sgb.kjwl.view.widget.MachineTypePopWindow;
import com.swgk.core.dialog.RoundCornerDialog;
import com.sgb.kjwl.viewmodel.self.publish.MachinePublishInModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MToast;
import com.swgk.core.util.NullStringToEmptyAdapterFactory;
import com.swgk.core.util.SharedPreferenceUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

import static com.sgb.kjwl.view.event.SuccessType.SUCC_MACHINE_IN;

/**
 * 机械求租发布
 */
@Deprecated
public class MachinePublishInActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private ActivityMachinePublishInBinding binding;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private final int MAX_LENGTH = 300;
    private CharSequence temp;
    private boolean isLoaded = false;
    private MachineTypePopWindow machineTypePopWindow;
    private AddChildEntity addChildEntity;
    private List<PublicTypeEntity> publicTypeEntityList;
    private List<DictEntity> dictEntityList;
    private List<PayType> payTypeList;
    // 一级联动数据
    private List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> addressEntityList;
    // 二级联动数据
    private List<List<AddressEntity<List<AddressEntity>>>> opt2;
    // 三级联动数据
    private List<List<List<AddressEntity>>> opt3;
    //城市列表
    private List<AddressEntity<List<AddressEntity>>> cityList;
    //区域列表
    private List<List<AddressEntity>> areaList;
    private int unitPosition;
    private int payTypePosition;
    private int cityPosition1;
    private int cityPosition2;
    private int cityPosition3;
    private Gson gson;
    private boolean isUpdate;
    @Inject
    MachinePublishInModel viewModel;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, MachinePublishInActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
    }

    @Override
    protected boolean statusBarDark() {
        return true;
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(MachinePublishInActivity.this, R.layout.activity_machine_publish_in);
        binding.setViewModel(viewModel);
        binding.itemTvConstructionPeriod.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvNum.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvPrice.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.backView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvType.setOnWholeItemClickListener(this);
        binding.itemTvUnit.setOnWholeItemClickListener(this);
        binding.itemTvPayType.setOnWholeItemClickListener(this);
        binding.itemTvTime.setOnWholeItemClickListener(this);
        binding.itemTvWorkPlace.setOnWholeItemClickListener(this);
    }

    @Override
    protected void init() {
        addChildEntity = new AddChildEntity();
        opt2 = new ArrayList<>();
        opt3 = new ArrayList<>();
        machineTypePopWindow = new MachineTypePopWindow(MachinePublishInActivity.this);
        machineTypePopWindow.setBgView(binding.grayLayout);
        machineTypePopWindow.setFilterResultClick(new MachineTypePopWindow.FilterResultClick() {
            @Override
            public void result(String key1, String key2, String key3) {
                addChildEntity.setFirstCategory(key1);
                addChildEntity.setSecondCategory(key2);
//                viewModel.addMachineInEntity.get().set(key1);
//                viewModel.addMachineInEntity.get().setSecondCategory(key2);
                binding.itemTvType.setContent(key3);
            }

            @Override
            public void dimiss() {

            }

            @Override
            public void queryChild(String pNo, String cNo, int position) {
                if (position == 1) {
                    viewModel.getMachineTypeModel(pNo);
                } else {
//                    viewModel.getDeviceAttr(pNo, cNo);
                }

            }
        });

        binding.markEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
                temp = charSequence;
            }

            @Override
            public void afterTextChanged(Editable editable) {
                binding.alreadyInputTv.setText(binding.markEt.getText().length() + "");
                if (temp.length() == MAX_LENGTH) {
                    Toast.makeText(MachinePublishInActivity.this, "只能输入300个字",
                            Toast.LENGTH_SHORT).show();
                }
            }
        });
        gson = new GsonBuilder().registerTypeAdapterFactory(new NullStringToEmptyAdapterFactory()).create();
        SharedPreferenceUtil.init(this);
        if (!"".equals(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DEVICE_PUBLISH_DATA, ""))) {
            String s = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DEVICE_PUBLISH_DATA, "");
            AddMachineInEntity addMachineInEntity = gson.fromJson(SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DEVICE_PUBLISH_DATA, ""), AddMachineInEntity.class);
            showSaveView(addMachineInEntity);
        }
    }

    //写死- - - -
    private void setPayType() {
        payTypeList = new ArrayList<>();
        PayType payType1 = new PayType();
        payType1.setName("协商付款");
        payType1.setType(0);
        PayType payType2 = new PayType();
        payType2.setName("现款");
        payType2.setType(1);
        PayType payType3 = new PayType();
        payType3.setName("结束付款");
        payType3.setType(2);
        payTypeList.add(payType1);
        payTypeList.add(payType2);
        payTypeList.add(payType3);
        showPayTypePop();
    }

    //发布成功调用
    public void publishSuccess() {
//        MToast.showToast(this, "发布成功");
        SuccessEntity successEntity = new SuccessEntity();
        successEntity.setType(SUCC_MACHINE_IN);
        successEntity.setButtonText("确定");
        successEntity.setTitle("发布成功");
        successEntity.setContent("您发布信息已提交成功，请前往机械发布页面查看");
        CommitSuccessActivity.start(this, successEntity);
    }

    public void showMachineTypePop() {
        machineTypePopWindow.showPopwindow(binding.itemTvType);
        machineTypePopWindow.setData(publicTypeEntityList);
    }

    public void showSaveView(AddMachineInEntity addMachineInEntity) {
        AddChildEntity addChildEntity = addMachineInEntity.getChildEntityList().get(0);
        viewModel.addMachineInEntity.set(addMachineInEntity);
        binding.itemTvType.setContent(addChildEntity.getCategoryName()
                + "-" + addChildEntity.getTypeName());
        binding.itemTvConstructionPeriod.setContent(addChildEntity.getWorkTime());
        binding.itemTvNum.setContent(addChildEntity.getNum());
        binding.itemTvUnit.setContent(addChildEntity.getPriceUnitName());
        binding.itemTvPrice.setContent(addChildEntity.getPrice());
        if ("0".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("协商付款");
        } else if ("1".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("现款");
        } else if ("2".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("结束付款");
        }
        binding.alreadyInputTv.setText(binding.markEt.getText().length() + "");
        binding.itemTvTime.setContent(DateUtils.stampToDate(addChildEntity.getApproachTime()));
        binding.itemTvWorkPlace.setContent(addMachineInEntity.getProvinceName() + "-" + "" + addMachineInEntity.getCityName() + "-" + addMachineInEntity.getAreaName());
    }

    public void showEditView(AddMachineInEntity addMachineInEntity) {
        AddChildEntity addChildEntity = addMachineInEntity.getChildEntityList().get(0);
        viewModel.addMachineInEntity.set(addMachineInEntity);
        binding.itemTvType.setContent(addChildEntity.getCategoryName()
                + "-" + addChildEntity.getTypeName());
        binding.itemTvConstructionPeriod.setContent(addChildEntity.getWorkTime());
        binding.itemTvNum.setContent(addChildEntity.getNum());
        binding.itemTvUnit.setContent(addChildEntity.getPriceUnitName());
        binding.itemTvPrice.setContent(addChildEntity.getPrice());
        if ("0".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("协商付款");
        } else if ("1".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("现款");
        } else if ("2".equals(addChildEntity.getPaymentType())) {
            binding.itemTvPayType.setContent("结束付款");
        }
        binding.alreadyInputTv.setText(binding.markEt.getText().length() + "");
        binding.itemTvTime.setContent(DateUtils.stampToDate(addChildEntity.getApproachTime()));
        binding.itemTvWorkPlace.setContent(addMachineInEntity.getProvinceName() + "-" + "" + addMachineInEntity.getCityName() + "-" + addMachineInEntity.getAreaName());

    }

    public void showUnitPop(List<DictEntity> dictEntityList) {
        this.dictEntityList = dictEntityList;
        showUnitPop();
    }

    private void showUnitPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishInActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = dictEntityList.get(options1).getName();
                binding.itemTvUnit.setContent(content);
                unitPosition = options1;
                addChildEntity.setPriceUnitNo(dictEntityList.get(options1).getNo());
                addChildEntity.setPriceUnitName(dictEntityList.get(options1).getName());
            }
        }).build();
        businessOption.setPicker(dictEntityList);
        businessOption.setSelectOptions(unitPosition);
        businessOption.show();
    }

    private void showPayTypePop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(MachinePublishInActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = payTypeList.get(options1).getName();
                binding.itemTvPayType.setContent(content);
                payTypePosition = options1;
                addChildEntity.setPaymentType(payTypeList.get(options1).getType() + "");
            }
        }).build();
        businessOption.setPicker(payTypeList);
        businessOption.setSelectOptions(payTypePosition);
        businessOption.show();
    }

    //时间选择器
    public void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(MachinePublishInActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                String format = sdf.format(date);
                binding.itemTvTime.setContent(format);
                addChildEntity.setApproachTime(format);
            }
        }).build();
        timePicker.show();
    }

    //服务范围
    public void showAddressPop
    (List<AddressEntity<List<AddressEntity<List<AddressEntity>>>>> datas) {
        this.addressEntityList = datas;
        if (isLoaded) {
            showCityPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    public void showCityPop() {
        //条件选择器
        CityPickView cityOption = new CityPickBuilder(MachinePublishInActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String areaName;
                if (opt3.get(options1).get(options2).get(options3) == null) {
                    areaName = "";
                } else {
                    areaName = opt3.get(options1).get(options2).get(options3).getName();
                    cityPosition3 = options3;
                    viewModel.addMachineInEntity.get().setAreaName(areaName);
                    viewModel.addMachineInEntity.get().setAreaNo(opt3.get(options1).get(options2).get(options3).getNo());
                }
                String content = addressEntityList.get(options1).getName()
                        + opt2.get(options1).get(options2).getName()
                        + areaName;
                binding.itemTvWorkPlace.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
                viewModel.addMachineInEntity.get().setProvinceName(addressEntityList.get(options1).getName());
                viewModel.addMachineInEntity.get().setProvinceNo(addressEntityList.get(options1).getNo());
                viewModel.addMachineInEntity.get().setCityName(opt2.get(options1).get(options2).getName());
                viewModel.addMachineInEntity.get().setCityNo(opt2.get(options1).get(options2).getNo());
            }
        }).build();
        cityOption.setPicker(addressEntityList, opt2, opt3);
        cityOption.setSelectOptions(cityPosition1, cityPosition2, cityPosition3);
        cityOption.show();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                finish();
                break;
            case R.id.next_view:
                if (TextUtils.isEmpty(binding.itemTvType.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请选择机械类型");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvConstructionPeriod.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写工期");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvNum.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写求租数量");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvUnit.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请选择价格单位");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPrice.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写求租价格");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPayType.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请选择结款方式");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvTime.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请选择场时间");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvWorkPlace.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请选择施工地点");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvTitle.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写信息标题");
                    return;
                } else if (TextUtils.isEmpty(binding.markEt.getText())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写求租详情");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPerson.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写联系人");
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
                    MToast.showToast(MachinePublishInActivity.this, "请填写联系电话");
                    return;
                } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
                    return;
                }
                List<AddChildEntity> childEntityList = new ArrayList<>();
                childEntityList.clear();
                addChildEntity.setWorkTime(binding.itemTvConstructionPeriod.getContent());
                addChildEntity.setNum(binding.itemTvNum.getContent());
                addChildEntity.setPrice(binding.itemTvPrice.getContent());
                addChildEntity.setPriceType("1");
                childEntityList.add(addChildEntity);
                viewModel.addMachineInEntity.get().setChildEntityList(childEntityList);
                if (viewModel.addMachineInEntity.get().getId() != null) {
                    viewModel.editMachineInModel();
                } else {
                    viewModel.addMachineInModel();
                }
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_type:
                if (publicTypeEntityList != null) {
                    showMachineTypePop();
                } else {
                    viewModel.getMachineTypeModel("");
                }
                break;
            case R.id.item_tv_unit:
                if (dictEntityList != null) {
                    showUnitPop();
                } else {
                    viewModel.getMachinePriceModel();
                }
                break;
            case R.id.item_tv_pay_type:
                if (payTypeList != null) {
                    showPayTypePop();
                } else {
                    setPayType();
                }
                break;
            case R.id.item_tv_time:
                showTimePop();
                break;
            case R.id.item_tv_work_place:
                if (addressEntityList != null) {
                    showCityPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEvent(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_IN_EDIT) {
            String id = (String) event.getMessageData();
            isUpdate = true;
            viewModel.getMachineInDetailModel(id);
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onEventPublish(MachinePublishEvent event) {
        if (event.getMessageTag() == EventConstant.EVENT_PUBLISH_MACHINE_IN_EDIT) {
            String id = (String) event.getMessageData();
            isUpdate = false;
            viewModel.getMachineInDetailModel(id);
            EventBus.getDefault().removeStickyEvent(event);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                // 子线程中解析省市区数据
                                initJsonData();
                            }
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showCityPop();
                    isLoaded = true;
                    break;

                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (AddressEntity<List<AddressEntity<List<AddressEntity>>>> entity : addressEntityList) {
            cityList = new ArrayList<>();
            areaList = new ArrayList<>();
            opt2.add(entity.getChildren());
            for (int i = 0; i < entity.getChildren().size(); i++) {
                cityList.add(entity.getChildren().get(i));
                List<AddressEntity> cityAreaList = new ArrayList<>();
                //如果无地区数据，建议添加空字符串，防止数据为null 导致三个选项长度不匹配造成崩溃
                if (entity.getChildren().get(i).getChildren() == null
                        || entity.getChildren().get(i).getChildren().size() == 0) {
                    cityAreaList.add(null);
                } else {
                    cityAreaList.addAll(entity.getChildren().get(i).getChildren());
                }
                areaList.add(cityAreaList);
            }
            opt3.add(areaList);
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    /***
     * 返回保存
     */
    private void backSave() {
        String dataJson = gson.toJson(viewModel.addMachineInEntity.get());
        SharedPreferenceUtil.init(this);
        String oldData = SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.DEVICE_PUBLISH_DATA, "");
        if ("".equals(oldData) || !dataJson.equals(oldData)) {
            showDialog(dataJson);
        } else {
            finish();
        }
    }

    /***
     * 是否保存
     */
    private void showDialog(String dataJson) {
        View view = View.inflate(getActivity(), R.layout.dialog_two_btn, null);
        final RoundCornerDialog roundCornerDialog = new RoundCornerDialog(getActivity(), 0, 0, view, R.style.RoundCornerDialog);
        if (!this.isFinishing() && !roundCornerDialog.isShowing()) {
            roundCornerDialog.show();
        }
        roundCornerDialog.setCanceledOnTouchOutside(false);// 设置点击屏幕Dialog不消失
//        roundCornerDialog.setOnKeyListener((dialogInterface, i, keyEvent) -> true);//设置点击返回键Dialog不消失

        TextView tv_message = view.findViewById(R.id.tv_message);
        TextView tv_logout_confirm = view.findViewById(R.id.tv_logout_confirm);
        TextView tv_logout_cancel = view.findViewById(R.id.tv_logout_cancel);
        tv_message.setText("是否保存数据");
        //确定
        tv_logout_confirm.setOnClickListener(v -> {
            SharedPreferenceUtil.getInstance().saveData(SharedPreferenceUtil.DEVICE_PUBLISH_DATA, dataJson);
            roundCornerDialog.dismiss();
            finish();
        });
        //取消
        tv_logout_cancel.setOnClickListener(v -> {
            roundCornerDialog.dismiss();
            finish();
        });
    }

    @Override
    public void onBackPressed() {
        if (!isUpdate) {
            backSave();
            return;
        } else {
            super.onBackPressed();
        }
    }
}

